import Mn from 'backbone.marionette';
import Bb from 'backbone';
import Radio from 'backbone.radio';

import StatusFormPopupView from '../../common/views/StatusFormPopupView.js';
import ExpenseModel from '../models/ExpenseModel.js';
import ExpenseKmModel from '../models/ExpenseKmModel.js';
import ExpenseTableView from './ExpenseTableView.js';
import ExpenseKmTableView from './ExpenseKmTableView.js';
import ExpenseFormPopupView from './ExpenseFormPopupView.js';
import ExpenseKmFormView from './ExpenseKmFormView.js';
import FileLinkPopupView from './FileLinkPopupView.js';
import ExpenseDuplicateFormView from './ExpenseDuplicateFormView.js';
import TotalView from './TotalView.js';
import TabTotalView from './TabTotalView.js';
import MessageView from '../../base/views/MessageView.js';
import LoginView from '../../base/views/LoginView.js';
import {displayServerSuccess, displayServerError} from '../../backbone-tools.js';
import ExpenseFormPopupViewWithFile from "./ExpenseFormPopupViewWithFile.js";
import NodeFileViewerPopupView
    from "../../common/views/NodeFileViewerPopupView";


/** Contruct the form popup title for a given expense
 *
 * @param expense: ExpenseBaseModel instance
 */
function makePopupTitle(expense) {
    let expenseLabel, actionLabel;
    if (expense.get('type') == 'km') {
        expenseLabel = 'dépense kilométrique';
    } else {
        expenseLabel = 'dépense';
    }

    if (expense.id) {
        actionLabel = 'Modifier';
    } else {
        actionLabel = 'Ajouter';
    }
    return `${actionLabel} une ${expenseLabel} (${expense.getCategoryLabel()})`
}

const MainView = Mn.View.extend({
   className: 'container-fluid page-content',
   template: require('./templates/MainView.mustache'),
   regions: {
       modalRegion: '.modalRegion',
       internalLines: '.internal-lines',
       internalKmLines: '.internal-kmlines',
       internalTotal: '.internal-total',
       activityLines: '.activity-lines',
       activityKmLines: '.activity-kmlines',
       activityTotal: '.activity-total',
       files: '.files',
       totals: '.totals',
       messages: {
           el: '.messages-container',
           replaceElement: true,
       }
   },
   ui:{
       internal: '#internal-container',
       activity: '#activity-container',
       modal: '.modalRegion',
   },
   childViewEvents: {
       'line:add': 'onLineAdd',
       'line:edit': 'onLineEdit',
       'line:delete': 'onLineDelete',
       'kmline:add': 'onKmLineAdd',
       'kmline:edit': 'onKmLineEdit',
       'kmline:delete': 'onLineDelete',
       'line:duplicate': 'onLineDuplicate',
       'kmline:duplicate': 'onLineDuplicate',
       'bookmark:add': 'onBookMarkAdd',
       'bookmark:delete': 'onBookMarkDelete',
       "status:change": 'onStatusChange',
       "attachment:delete": 'onAttachmentDelete',
       "attachment:link_to_expenseline": 'onAttachmentLink',
       "preview:displayStatusChange": 'onPreviewDisplayStatusChange',
   },
   templateContext(){
   	return {
   		internalDescription: this.categories[0].description, 
   		externalDescription: this.categories[1].description,
   		internalTabLabel: this.categories[0].label, 
   		externalTabLabel: this.categories[1].label,
   		}
   },
   initialize(){
       this.facade = Radio.channel('facade');
       this.config = Radio.channel('config');
       this.categories = this.config.request('get:options', 'categories');
       this.edit = this.config.request('get:form_section', 'general')['edit'];
       this.listenTo(this.facade, 'status:change', this.onStatusChange);
       this.listenTo(this.facade, 'show:preview', this.onShowPreview);
   },
   onLineAdd(childView, modelAttributes, withAttachment){
       /*
        * Launch when a line should be added
        *
        * :param attributes (optional) : initial Line model attributes
        */
       let model = new ExpenseModel(modelAttributes || {});
       this.showLineForm(model, true, withAttachment);
   },
   onKmLineAdd(childView, modelAttributes){
       let model = new ExpenseKmModel(modelAttributes || {});
       this.showKmLineForm(model, true);
   },
   showModal(view, size){
       if (size === undefined) {
           size = 'middle';
       }
       this.resizeModal(size);
       this.showChildView('modalRegion', view);
   },
   onShowPreview(nodeFile) {
       let view = new NodeFileViewerPopupView({
           file: nodeFile,
           popupTitle: "Justificatif",
       });
       this.showModal(view, 'large');
   },
   resizeModal(size){
       const sizes = 'size_small size_middle size_extralarge size_large size_full';
       this.ui.modal.removeClass(sizes).addClass(`size_${size}`);
   },
   onLineEdit(childView){
       this.showLineForm(childView.model, false);
   },
   onKmLineEdit(childView){
       this.showKmLineForm(childView.model, false);
   },
   onAttachmentLink(model){
       this.showFileLinkForm(model);
   },
   showFileLinkForm(model){
       let view = new FileLinkPopupView({
           model: model,
           linesCollection: this.facade.request('get:collection', 'lines'),
       });
       this.showModal(view);
   },
   showLineForm(model, add, withAttachment){
       const params = {
           title: makePopupTitle(model),
           buttonTitle: add ? 'Ajouter' : 'Modifier',
           add:add,
           model:model,
           destCollection: this.facade.request('get:collection', 'lines'),
       };
       let view;
       if (withAttachment){
            view = new ExpenseFormPopupViewWithFile(params);
       } else {
            view = new ExpenseFormPopupView(params);
       }
       // File viewer is displayed only if we have one and only one attachment
       if ((model.get('files') || []).length === 1) {
           this.showModal(view, 'full');
       } else {
           this.showModal(view, 'middle');
       }
   },
   showKmLineForm(model, add){
       var view = new ExpenseKmFormView({
           title: makePopupTitle(model),
           buttonTitle: add ? 'Ajouter' : 'Modifier',
           add:add,
           model:model,
           destCollection: this.facade.request('get:collection', 'kmlines'),
       });
       this.showModal(view);
   },
   showDuplicateForm(model){
       var view = new ExpenseDuplicateFormView({model: model});
       this.showModal(view);
   },
   onLineDuplicate(childView){
       this.showDuplicateForm(childView.model);
   },
   onDeleteSuccess: function(){
       displayServerSuccess("Vos données ont bien été supprimées");
   },
   onDeleteError: function(){
       displayServerError("Une erreur a été rencontrée lors de la " +
                           "suppression de cet élément");
   },
   onLineDelete: function(childView){
       var result = window.confirm("Êtes-vous sûr de vouloir supprimer cette dépense ?");
       if (result){
           childView.model.destroy(
               {
                   success: this.onDeleteSuccess,
                   error: this.onDeleteError
               }
           );
       }
   },
   onPreviewDisplayStatusChange: function(previewDisplayed) {
       if (previewDisplayed) {
           this.resizeModal('full');
       } else {
           this.resizeModal('middle');
       }
   },
   onAttachmentDelete: function(model) {
       let confirmed = window.confirm('Êtes-vous sûr de vouloir supprimer ce justificatif ?');
       if (confirmed) {
           model.destroy({
               success: this.onDeleteSuccess,
               error: this.onDeleteError
           });

       }
   },
   onBookMarkAdd(childView){
       var collection = this.facade.request('get:bookmarks');
       collection.addBookMark(childView.model);
       childView.highlightBookMark();
   },
   onBookMarkDelete(childView){
       var result = window.confirm("Êtes-vous sûr de vouloir supprimer ce favoris ?");
       if (result){
           childView.model.destroy(
               {
                   success: this.onDeleteSuccess,
                   error: this.onDeleteError
               }
           );
       }
   },
   showTab(categoryId, regularRegion, kmsRegion){
       let linesCollection = this.facade.request(
           'get:collection',
           'lines',
       );
       let filesCollection = this.facade.request(
           'get:collection',
           'attachments',
       );

       var view = new ExpenseTableView({
           collection: linesCollection,
           filesCollection: filesCollection,
           category: categoryId,
           edit: this.edit,
       });
       this.showChildView(regularRegion, view);

       var km_type_options = this.config.request(
            'get:options',
            'expensekm_types',
       );
       if (!_.isEmpty(km_type_options)){
           let collection = this.facade.request(
               'get:collection',
               'kmlines'
           );
           view = new ExpenseKmTableView({
               collection: collection,
               category: categoryId,
               edit: this.edit,
           });
           this.showChildView(kmsRegion, view);
       }
   },
   showMessages(){
       var model = new Bb.Model();
       var view = new MessageView({model: model});
       this.showChildView('messages', view);
   },
   showTotals(){
       let model = this.facade.request('get:totalmodel');
       var view = new TotalView({model: model});
       this.showChildView('totals', view);

       view = new TabTotalView({model: model, category: 1});
       this.showChildView('internalTotal', view);
       view = new TabTotalView({model: model, category: 2});
       this.showChildView('activityTotal', view);
   },
    showLogin: function(){
        var view = new LoginView({});
        this.showModal(view, 'small');
    },
   onRender(){
       this.showTab(this.categories[0], 'internalLines', 'internalKmLines');
       this.showTab(this.categories[1], 'activityLines', 'activityKmLines');
       this.showTotals();
       this.showMessages();
   },
   onStatusChange(model){
       console.log("Status change");
       var view = new StatusFormPopupView({action: model});
       this.showModal(view, 'small');
   },
});
export default MainView;
